/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.uct.common.filter  
 */
package com.apache.uct.common.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.apache.client.IBaseReplaceCard;
import com.apache.client.UctCoreClient;
import com.apache.passport.common.PassportHelper;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.Role;

/**
 * description:  用户中心客户端filter
 * @author dwusoft 创建时间：2015-3-30  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
public class UctClientFilter extends UctSupperFilter {

	private Logger logger = Logger.getLogger(UctClientFilter.class);

	//未知,uct_client.properties
	//	private Map<String, Lock> lockMap = new ConcurrentHashMap<String, Lock>();
	//登录后可访问,uct_client.properties
	private String onlyLoginUrl = "";
	//系统名称
	private String sysEname = "";
	private String sessionKey = "loginUser";
	private Map<String, ArrayList<String>> whiteMap = new HashMap<String, ArrayList<String>>();
	//错误页面地址
	private String errorPage = "";

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 */
	public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest request = (HttpServletRequest) srequest;
		HttpServletResponse response = (HttpServletResponse) sresponse;

		response.setCharacterEncoding("UTF-8");
		response.setDateHeader("expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("pragma", "no-cache");
		request.setCharacterEncoding("UTF-8");
		LoginUser loginUser = null;
		//获取当前访问路径
		String path = request.getServletPath();

		//获取cookie值
		String cookieValue = PassportHelper.getInstance().getCurrCookie(request);
		logger.debug(cookieValue);
		//如果cookie为空,则从session中删除用户对象
		if (ToolsUtil.isNull(cookieValue)) {
			boolean isMobile = JudgeIsMoblie(request);
			if (isMobile) {
				String tokenId = request.getParameter("tokenId");
				if (ToolsUtil.isNotNull(tokenId)) {
					chain.doFilter(request, response);
					return;
				}
			} else {
				clearLoginInfo(request, response);
			}
		} else {
			//通过token及用户名去uc获取用户对象
			loginUser = (LoginUser) request.getSession().getAttribute(sessionKey);
			if (null == loginUser) {
				String value = PassportHelper.getInstance().getCurrCookie(request, "_uc.sso");
				if (ToolsUtil.isNull(value)) {
					response.sendRedirect(request.getContextPath() + path);
					return;
				}
				//value = DesUtils.getInstance().decrypt(value);//解密
				loginUser = UctCoreClient.getLoginUserFromUserCenterSso("", cookieValue);
			} else {
				String tokenId = String.valueOf(request.getSession().getAttribute("cookieToken"));
				if (!cookieValue.equalsIgnoreCase(tokenId)) {//判断是否变更了新用户
					String value = PassportHelper.getInstance().getCurrCookie(request, "_uc.sso");
					///value = DesUtils.getInstance().decrypt(value);
					loginUser = setLoginUser(request, "");
				}
			}
		}

		if (!ToolsUtil.isEmpty(loginUser)) {
			request.getSession().setAttribute(sessionKey, loginUser);//获取session中信息
			if ("T".equals(ToolsUtil.getInstance().getClientValueByKey("local_user"))) {//用户换证处理操作
				try {
					String reflectPath = ToolsUtil.getInstance().getClientValueByKey("reflect_path");
					Class<?> clazz = Class.forName(reflectPath);
					IBaseReplaceCard replaceCard = (IBaseReplaceCard) clazz.newInstance();
					boolean flag = replaceCard.replaceCard(loginUser, request, response);//数据插入到本地，并且换证
					if (!flag) {
						response.sendRedirect(request.getContextPath() + "/");
						return;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (ToolsUtil.isEmpty(request.getSession().getAttribute("loginUserRoles"))) {
				List<Role> roles = PBOSSOTools.getRolesForLoginUser(request);//获取用户角色列表
				if (ToolsUtil.isEmpty(roles)) {
					request.getSession().setAttribute("loginUserRoles", roles);
				}
			}
		}
		//白名单处理
		if (unlockPath(path)) {
			chain.doFilter(request, response);
			return;
		}
		/**白名单处理*/
		String whiteUrl = "/error.action,/errorPage," + ToolsUtil.getInstance().getClientValueByKey("white_url");
		if (StrUtil.isNotNull(whiteUrl)) {
			String[] wus = whiteUrl.split(",");
			for (int i = 0; i < wus.length; i++) {
				String wurl = wus[i];
				if (StrUtil.isNotNull(wurl)) {
					if (path.startsWith(wurl)) {
						chain.doFilter(request, response);
						return;
					}
				}
			}
		}
		if (ToolsUtil.isEmpty(loginUser)) {//退出
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath();
			response.sendRedirect(basePath + "/");
			return;
		}

		//只需登录的url地址处理
		String NORIGHT_URL = UctCoreClient.getConf_Map().get("noright_url");
		if (ToolsUtil.isNotNull(onlyLoginUrl) || ToolsUtil.isNotNull(NORIGHT_URL)) {
			String str = NORIGHT_URL + onlyLoginUrl;
			String[] wus = str.split(",");
			for (int i = 0; i < wus.length; i++) {
				String wurl = wus[i];
				if (ToolsUtil.isNotNull(wurl)) {
					if (path.startsWith(wurl)) {
						chain.doFilter(request, response);
						return;
					}
				}
			}
		}
		//黑名单处理 ,循环黑名单,只要访问的路径包含黑名单定义,则需要检查,只要检查不通过,则拦截
		if ("1".equals(ToolsUtil.getInstance().getClientValueByKey("usage_patterns"))) {
			if (!canAccessSupper(loginUser, path)) {//验证访问权限
				request.getSession().setAttribute("errorMsg", "对不起,您没有访问权限!!");
				response.sendRedirect(request.getContextPath() + errorPage);
				return;
			}
		}
		chain.doFilter(request, response);
	}

	private LoginUser setLoginUser(HttpServletRequest request, String userEname) {
		String cookieValue = PassportHelper.getInstance().getCurrCookie(request);
		LoginUser loginUser = UctCoreClient.getLoginUserFromUserCenterSso(userEname, cookieValue);
		request.getSession().setAttribute("cookieToken", cookieValue);
		return loginUser;
	}

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)  
	 */
	public void init(FilterConfig arg0) throws ServletException {
		//登录后可访问,uct_client.properties
		onlyLoginUrl = ToolsUtil.getInstance().getClientValueByKey("only_login_url");
		//系统名称
		sysEname = ToolsUtil.getInstance().getClientValueByKey("sysEname");

		logger.info("系统:" + sysEname);
		if (ToolsUtil.isNull(sysEname)) {
			throw new ServletException("系统标识sysEname为空");
		}
		//资源权限从数据库读取,如果某个资源绑定了对应的权限,则要符合权限判断; 如果没有绑定权限,则默认为登录权限.
		//getSysLock();
		//错误页面地址
		errorPage = StrUtil.doNull(arg0.getInitParameter("errorPage"), "/error.action");
	}

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see javax.servlet.Filter#destroy()  
	 */
	public void destroy() {
	}
}
